package tweeks.menu.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import tweeks.menu.domain.Menu;
import tweeks.menu.persistence.MenuMapper;

@Service("MenuServiceImpl")
public class MenuServiceImpl implements MenuService {
	
	@Resource(name="MenuMapper")
	private MenuMapper menuMapper;

	@Override
	public List<Menu> selectMenu(Menu menu) {
		return menuMapper.selectMenu(menu);
	}

	@Override
	public void createMenu(Menu menu) {
		menuMapper.createMenu(menu);
	}

	@Override
	public void deleteMenu(Menu menu) {
		menuMapper.deleteMenu(menu);
	}

	@Override
	public void modifyMenu(Menu menu) {
		menuMapper.modifyMenu(menu);
	}
	
	@Override
	public List<Menu> generateMenuList(Menu menu) {
		List<Menu> org = menuMapper.selectMenu(null);
		List<Menu> list = new ArrayList<Menu>();
		if (menu.getId() == null) {
			menu = new Menu();
			menu.setName("*");
		}
		List<Menu> result = menuMapper.selectMenu(menu);
		if (result != null && result.size() > 0) {
			list.add(result.get(0));
			addChildItem(org, list, result.get(0), 1);
		}
		return list;
	}
	
	public void addChildItem(List<Menu> org, List<Menu> target, Menu parent, int level) {
		for (Menu item : org) {
			if (item.getParentId() != null && item.getParentId().equals(parent.getId())) {
				item.setLevel(level);
				target.add(item);
				addChildItem(org, target, item, level + 1);
			}
		}
	}

	@Override
	public Menu generateMenuTree(Menu menu) {
		List<Menu> org = menuMapper.selectMenu(null);
		if (menu.getId() == null) {
			menu = new Menu();
			menu.setName("*");
		}
		Menu parent = null;
		List<Menu> results = menuMapper.selectMenu(menu);
		if (results != null && results.size() > 0) {
			parent = results.get(0);
			addChildNode(org, parent, 1);
		}
		return parent;
	}

	public void addChildNode(List<Menu> org, Menu parent, int level) {
		List<Menu> children = new ArrayList<Menu>();
		for (Menu item : org) {
			if (item.getParentId() != null && item.getParentId().equals(parent.getId())) {
				item.setLevel(level);
				children.add(item);
				addChildNode(org, item, level + 1);
			}
		}
		parent.setChildren(children);
	}
}